﻿using System;
using System.Collections.Specialized;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Web;
using System.Windows.Forms;

namespace SoundKeyCreator
{
    public partial class Form1 : Form
    {
        //下载

        private readonly StringCollection scGe = new StringCollection {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
        private readonly StringCollection scWei = new StringCollection {"", "十", "百", "千"};

        public Form1()
        {
            InitializeComponent();
        }

        [DllImport("urlmon.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern Int32 URLDownloadToFile(
            [MarshalAs(UnmanagedType.IUnknown)] object pCaller,
            [MarshalAs(UnmanagedType.LPWStr)] string szURL,
            [MarshalAs(UnmanagedType.LPWStr)] string szFileName,
            Int32 dwReserved,
            IntPtr lpfnCB);

        private bool DownFileFormUrl(string url, string saveFilePath)
        {
            if (File.Exists(saveFilePath)) File.Delete(saveFilePath);
            int iresult = URLDownloadToFile(null, url, saveFilePath, 0, IntPtr.Zero);
            return (iresult != 0);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            wb.Navigate("http://translate.google.cn/translate_tts?ie=UTF-8&q=One&tl=En");
        }


        private void btnCreateCnKey_Click(object sender, EventArgs e)
        {
            var sb = new StringBuilder();
            int maxNum = 9999;
            int fileAmount = 0;
            for (int i = 1; i <= maxNum; i++)
            {
                string cnNum = "";
                string strNum = i.ToString();
                char[] cc = strNum.ToCharArray();
                int weiIndex = 0;
                int ingronLastIndex = strNum.Length;
                int lastZeroIndex = strNum.Length;
                for (int k = strNum.Length - 1; k > -1; k--)
                {
                    if (cc[k] == '0' && k == ingronLastIndex - 1)
                        ingronLastIndex = k;

                    cnNum = (cc[k] == '0' && (k == ingronLastIndex || k == lastZeroIndex - 1)
                                 ? ""
                                 : scGe[Convert.ToInt16(cc[k].ToString())]) +
                            ((cc[k] == '0' && weiIndex > 0) ? "" : scWei[weiIndex]) + cnNum;
                    if (cc[k] == '0') lastZeroIndex = k;
                    weiIndex++;
                }
                sb.Append(cnNum + "\r\n");
                if (i%3000 == 0 || i == maxNum)
                {
                    fileAmount++;
                    string dir = AppDomain.CurrentDomain.BaseDirectory + "\\CnKeys";
                    if (!Directory.Exists(dir))
                        Directory.CreateDirectory(dir);
                    var sw = new StreamWriter(dir + "\\CnKey_" + fileAmount.ToString().PadLeft(3, '0') + ".txt", false);
                    try
                    {
                        sw.Write(sb.ToString());
                    }
                    finally
                    {
                        sw.Close();
                    }
                    sb = new StringBuilder();
                }
            }

            MessageBox.Show("OK");
        }

        private void btnDownSoundFiles_Click(object sender, EventArgs e)
        {
            MessageBox.Show(DownSounds("En"));
        }

        private string DownSounds(string langKey)
        {
            var scUrl = new StringCollection();
            var sr =
                new StreamReader(AppDomain.CurrentDomain.BaseDirectory + langKey + "Keys\\" + langKey + "Key_001.txt",
                                 Encoding.UTF8);
            try
            {
                while (sr.Peek() > 0)
                {
                    string strVal = sr.ReadLine();
                    if (!string.IsNullOrEmpty(strVal))
                    {
                        //http://translate.google.cn/translate_tts?ie=UTF-8&q=Twenty-two&tl=en
                        strVal = HttpUtility.UrlPathEncode(strVal);
                        string strUrl = "http://translate.google.cn/translate_tts?ie=UTF-8&q=" + strVal + "&tl=" +
                                        langKey;
                        scUrl.Add(strUrl);
                    }
                }
            }
            finally
            {
                sr.Close();
                sr.Dispose();
            }
            var dir = AppDomain.CurrentDomain.BaseDirectory + langKey + "Urls";
            if(!Directory.Exists(dir)) Directory.CreateDirectory(dir);
            var sw = new StreamWriter(dir + "\\" + langKey + "Urls_001.txt",false);
            try
            {
                for (int i = 0; i < scUrl.Count; i++)
                {
                    sw.WriteLine(scUrl[i]);
                }
            }
            finally
            {
                sw.Close();
                sw.Dispose();
            }
            for (int i = 0; i < scUrl.Count; i++)
            {
                var strSoundFilePath = AppDomain.CurrentDomain.BaseDirectory + langKey + "SoundFiles\\" +
                                       (i + 1).ToString().PadLeft(4, '0') + ".mp3";
                if(File.Exists(strSoundFilePath)) continue;
                var startDate = DateTime.Now;
                DownFileFormUrl(scUrl[i],strSoundFilePath);
                var sp = DateTime.Now - startDate;
                if (sp.TotalSeconds > 5)
                {
                    MessageBox.Show("Not Finish");
                    return "Not Finish";
                }
                else
                    Thread.Sleep(Convert.ToInt16(txtSleepTime.Text));
            }
            return ("Down Ok");
        }

        private void btnDownSoundsPt_Click(object sender, EventArgs e)
        {
            MessageBox.Show(DownSounds("Pt"));
        }

        private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            StreamReader Myreader = new StreamReader(wb.DocumentStream);
            StreamWriter MyWriter = new StreamWriter("e:\\t.mp3");
            MyWriter.Write(Myreader.ReadToEnd());
        }
    }
}